#!
# by jzhang @ 09:38 2004-08-15  mailto:jzhang533@gmail.com
# used to filter out unwanted links from an array by RE based rule
#

use warnings;
use strict;

package jzhang::LinkFilter;
my @Exporter = qw(new filter include);

sub new {
    my $class = shift;
    my $self = {};
    bless $self,$class;
    return $self->_init(@_);
}

sub _init {
    my $self = shift;
    $self->{'+'}     = [];
    $self->{'-'}     = [];

    if (@_ != 0) {
        if (ref $_[0] eq 'HASH') {
            my $hash=$_[0];
            foreach my $key (keys %$hash) {
                $self->{lc($key)}=$hash->{$key};
            }
        } else {
            my %args = @_;
            foreach my $key (keys %args) {
                $self->{lc($key)}=$args{$key};
            }
        }
    }

    return undef unless $self->{'rulefilename'};
    open RF, $self->{'rulefilename'} or return undef;
    while(<RF>){
        chomp;
        next if /^\s*$/;
        next if /^\#/;
        if(/^\+(.*)$/){
            push @{$self->{'+'}},$1;
        }elsif(/^-(.*)$/){
            push @{$self->{'-'}},$1;
        }
    }
    close RF;
    return $self;
}

# accept an array reference
sub filter {
    my $self = shift;
    my @filtered;
    foreach my $link (@{$_[0]}){
        push @filtered,$link if $self->include($link);
    }
    @filtered;
}

# check include or ignore a link
sub include{
    my $self = shift;
    for my $re (@{$self->{'-'}}){
        return 0 if $_[0] =~ /$re/i;
    }
    for my $re (@{$self->{'+'}}){
        return 1 if $_[0] =~ /$re/i;
    }
    return 0;
}

1;
